package uk.gov.swmprobation.cplite;

import android.accounts.AccountManager;
import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.widget.Toast;

import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.MapBuilder;
import com.google.android.gms.common.AccountPicker;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class SetFragment extends PreferenceFragment {
	
	Context context;
	SharedPreferences sharedPref;
	Preference emailPreference;

	public SetFragment(){
		context = MyApplication.getContext();
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
        
        // Load the preferences from an XML resource
        addPreferencesFromResource(R.xml.preferences);

        OnPreferenceChangeListener updatedNote = new OnPreferenceChangeListener(){

			@Override
			public boolean onPreferenceChange(Preference preference,
					Object newValue) {
				preference.setSummary((CharSequence) newValue);
				return true;
			}
        	
        };
        
        emailPreference = (Preference) findPreference("email");
        String accountName = sharedPref.getString("user_email", "No email selected");
        emailPreference.setSummary(accountName);
        
        Preference prefUserCode = findPreference("pref_user_code");
        prefUserCode.setSummary(sharedPref.getString("pref_user_code", "General Public"));
        prefUserCode.setOnPreferenceChangeListener(updatedNote);
        Preference prefWaitWifi = (Preference)findPreference("pref_wait_wifi");
        int wifiCode = Integer.parseInt(sharedPref.getString("pref_wait_wifi", "2"));
        prefWaitWifi.setSummary(SettingsActivity.wifiText(wifiCode));
        prefWaitWifi.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){

			@Override
			public boolean onPreferenceChange(Preference preference,
					Object newValue) {
				preference.setSummary((CharSequence) SettingsActivity.wifiText(Integer.valueOf(newValue.toString())));
				return true;
			}
        	
        });
        
        Preference prefResetHints = (Preference)findPreference("resetHints");
        prefResetHints.setOnPreferenceClickListener(new OnPreferenceClickListener(){

			@Override
			public boolean onPreferenceClick(Preference preference) {
				sharedPref.edit().putBoolean(SettingsActivity.submitHintTitle, true).commit();
				sharedPref.edit().putBoolean(SettingsActivity.startHintTitle, true).commit();
				sharedPref.edit().putBoolean(CreateProject.thankYouTitle, true).commit();
				Toast.makeText(context, "All Hints will be shown", Toast.LENGTH_SHORT).show();
				return false;
			}
        	
        });
        
        ///Preference prefEmail = (Preference)findPreference("email");
        emailPreference.setOnPreferenceClickListener(new OnPreferenceClickListener(){

			@Override
			public boolean onPreferenceClick(Preference preference) {
				try {
			        Intent intent = AccountPicker.newChooseAccountIntent(null, null,
			        		new String[] { "com.google", "com.android.email", "com.outlook.Z7.eas" }, false, null, null, null, null);
			        startActivityForResult(intent, SettingsFragment.REQUEST_CODE);
			    } catch (ActivityNotFoundException e) {
			        // TODO
			    }
				return false;
			}
        	
        });
        
    }
	
	@Override
	public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == SettingsFragment.REQUEST_CODE){
	    	EasyTracker easyTracker = EasyTracker.getInstance(context);
		    if (resultCode == SettingsFragment.RESULT_OK) {
		        String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
		        sharedPref.edit().putString("user_email", accountName).commit();
		        emailPreference.setSummary(accountName);
		        easyTracker.send(MapBuilder
		    		      .createEvent("user_action",     // Event category (required)
		    		                   "email_entry",  // Event action (required)
		    		                   "entered",   // Event label
		    		                   null)            // Event value
		    		      .build()
		    		  );
		    } else {
		    	easyTracker.send(MapBuilder
		    		      .createEvent("user_action",     // Event category (required)
		    		                   "email_entry",  // Event action (required)
		    		                   "not_entered",   // Event label
		    		                   null)            // Event value
		    		      .build()
		    		  );
		    }
		}
	}
	
}
